package cn.com.surker.wechat;

import cn.com.surker.common.HttpRequestHelper;
import cn.com.surker.redis.RedisUtils;
import cn.com.surker.spring.SpringContextHolder;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @Author lucky
 * @create 2021年03月24 14:53
 * @desc
 */
public class WechatProcessGroupApi {

    private static Logger log = LoggerFactory.getLogger(WechatProcessGroupApi.class);

    /**企业微信的**/
    public static String corpID = "wwd85ae41a2d988bc8";
    /**企业微信密匙**/
    public static String corpSecret = "a8aJrELgeMfTeb0YQHi1waaQSMs1NZm1BxRbe2cYkjg";
    /**应用ID**/
    public static String agentId = "3010040";
    /**缓存键**/
    public static String accessTokenKey = "process_cloud_access_token";

    public static String ticketKey = "group_process_cloud_js_ticket";
    /**缓存时间**/
    public static Long sessionExpired = 7200L;

    public static void main(String[] args){
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpID + "&corpsecret=" + corpSecret;
//        String res = HttpRequestHelper.get(url);
//        JSONObject obj = JSONObject.parseObject(res);

        Date start = DateUtil.convertDate("2023-11-21 08:05:00");
        Date end = DateUtil.convertDate("2023-11-21 10:20:00");
        Long startTime = start.getTime() / 1000;
        Long endTime = end.getTime() / 1000;
        System.out.println(startTime + "   " + endTime);
//        JSONObject jo = getExamineOrderId(corpID, corpSecret, startTime, endTime,  100);
        JSONObject jo = getOrderDetail(corpID, corpSecret, "202311210002");
        System.out.println(jo);
    }

    public static JSONObject getOrderDetail(String corpid, String secret, String orderId) {
        if (StringUtils.isNull(corpid))
            corpid = corpID;
        if (StringUtils.isNull(secret))
            secret = corpSecret;
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        String tokenKey = corpid + "_" + accessTokenKey;
        String accessToken = "XQIKpYAt_gzoM6JhZhgSLrzXchP-SIWqHSFLbsrUATsm5VRUWcpKeEWldQFNBMLJenmeKxeCj_uwqtNeHy8nJNewZvwiTjUA_A74L9h92ld5oSA0wnU3seGTrkY166pgXko7VmXMHiDKzna9wLCiImgRYltmm7aaFSJjZLKBMtBxT1gVTgx7vaYQUm9M_8_CFIMG_W-ecYxlTbu1xAYHyg";
        if(redisUtils.exists(tokenKey))
            accessToken = StringUtils.convertString(redisUtils.get(tokenKey));
        else
            accessToken = loadGroupToken(corpid, secret);
        try {
            JSONObject jsonObject = new JSONObject();

//            jsonObject.put("access_token", accessToken);
            jsonObject.put("sp_no", orderId);
            /**消息请求地址**/
            String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovaldetail?access_token=" + accessToken;
            /**请求结果**/
            String result = HttpRequestHelper.sendJsonPost(postUrl, jsonObject.toJSONString());
            JSONObject obj = JSONObject.parseObject(result);
            Integer code = obj.getInteger("errcode");
            System.out.println(result);
            if(code == 0){
                return obj;

            } else if (code == 42001 || code == 40014){//token失效
                log.error("同步企业微信订单详情token失效，重新获取token");
                redisUtils.remove(tokenKey);
                loadGroupToken(corpid, secret);
                return getOrderDetail(corpid, secret, orderId);
            } else {
                log.error("同步企业微信订单详情失败：" + result);
                return null;
            }
        } catch (Exception e) {
            log.error("同步企业微信订单详情失败：" + e.getMessage(), e);
        }
        return null;
    }

    /**
     * 批量获取审批订单号
     * @param corpid
     * @param secret
     * @param startTime 开始时间
     * @param endTime 结束时间(跨度不能大于8天)
     * @param size
     * @return
     */
    public static JSONObject getExamineOrderId(String corpid, String secret, Long startTime, Long endTime, Integer size) {
        if (StringUtils.isNull(corpid))
        corpid = corpID;
        if (StringUtils.isNull(secret))
            secret = corpSecret;
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        String tokenKey = corpid + "_" + accessTokenKey;
        String accessToken = "XQIKpYAt_gzoM6JhZhgSLrzXchP-SIWqHSFLbsrUATsm5VRUWcpKeEWldQFNBMLJenmeKxeCj_uwqtNeHy8nJNewZvwiTjUA_A74L9h92ld5oSA0wnU3seGTrkY166pgXko7VmXMHiDKzna9wLCiImgRYltmm7aaFSJjZLKBMtBxT1gVTgx7vaYQUm9M_8_CFIMG_W-ecYxlTbu1xAYHyg";
        if(redisUtils.exists(tokenKey))
            accessToken = StringUtils.convertString(redisUtils.get(tokenKey));
        else
            accessToken = loadGroupToken(corpid, secret);
        try {
            JSONObject jsonObject = new JSONObject();

            jsonObject.put("access_token", accessToken);
            jsonObject.put("starttime", startTime);
            jsonObject.put("endtime", endTime);
            jsonObject.put("new_cursor", "");
            jsonObject.put("size", size);
            /**消息请求地址**/
            String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovalinfo?access_token=" + accessToken;
            /**请求结果**/
            String result = HttpRequestHelper.sendJsonPost(postUrl, jsonObject.toJSONString());
            JSONObject obj = JSONObject.parseObject(result);
            Integer code = obj.getInteger("errcode");
            System.out.println(result);
            if(code == 0){
                return obj;

            } else if (code == 42001 || code == 40014){//token失效
                log.error("同步企业微信审批token失效，重新获取token");
                redisUtils.remove(tokenKey);
                loadGroupToken(corpid, secret);
                return getExamineOrderId(corpid, secret, startTime, endTime, size);
            } else {
                log.error("同步企业微信审批失败：" + result);
                return null;
            }
        } catch (Exception e) {
            log.error("同步企业微信审批失败：" + e.getMessage(), e);
        }
        return null;
    }

    /**
     *  加载企业微信的token
     * @param corpid 企业微信应用ID
     * @param secret 应用secret
     */
    public static String loadGroupToken(String corpid, String secret) {
        if (StringUtils.isNull(corpid))
            corpid = corpID;
        if (StringUtils.isNull(secret))
            secret = corpSecret;
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        /**缓存key**/
        String tokenKey = corpid + "_" + accessTokenKey;
        if (redisUtils.exists(tokenKey))
            return StringUtils.convertString(redisUtils.get(tokenKey));

        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + secret;

        try {
            String res = HttpRequestHelper.get(url);
            JSONObject obj = JSONObject.parseObject(res);
            log.error("企业微信获取access_token:{},token_url:{}", res, url);
            if("ok".equals(obj.getString("errmsg"))){
                log.info("验证后的access_token:{}", obj.getString("access_token"));
                redisUtils.set(tokenKey, obj.getString("access_token"), sessionExpired);
                return obj.getString("access_token");
            } else {
                log.error("获取企业微信API token失败：" + res);
                return "";
            }
        } catch (Exception e) {
            log.error("获取企业微信API token失败：" + e.getMessage(), e);
            return "";
        }
    }
}
